package com.hulk.ratel.common.util;

import org.joda.time.DateTime;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 日期、时间类
 * 
 * @author cmt
 * 
 */
public class DateUtil {
	
	

	/**
	 * 日期转换
	 * 
	 * @author
	 * @param time
	 * @param fmt
	 *            :yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String formatTime(Timestamp time, String fmt) {
		if (time == null) {
			return "";
		}
		SimpleDateFormat myFormat = new SimpleDateFormat(fmt);
		return myFormat.format(time);
	}

	/**
	 * 格式化日期
	 * 
	 * @author
	 * @param date
	 * @param fmt
	 * @return
	 * @throws Exception
	 */
	public static String formatDate(Date date, String fmt)  {
		if (date == null) {
			return "";
		}
		SimpleDateFormat myFormat = new SimpleDateFormat(fmt);
		return myFormat.format(date);
	}
	
	/**
	 * 获取当前日期
	 * 
	 * @author
	 * @return
	 */
	public static Date getDate() {
		Calendar calendar = Calendar.getInstance();
		return calendar.getTime();
	}

	/**
	 * 获取系统当前时间（秒）
	 * 
	 * @author
	 * @return
	 */
	public static Timestamp getTime() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		String mystrdate = myFormat.format(calendar.getTime());
		return Timestamp.valueOf(mystrdate);
	}

	/**
	 * 获取当前日期(时间00:00:00)
	 * 
	 * @author
	 * @return
	 */
	public static Timestamp getDateFirst() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		Calendar calendar = Calendar.getInstance();
		String mystrdate = myFormat.format(calendar.getTime());
		return Timestamp.valueOf(mystrdate);
	}

	/**
	 * 获取当前日期(时间23:59:59)
	 * 
	 * @author
	 * @return
	 */
	public static Timestamp getDateLast() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
		Calendar calendar = Calendar.getInstance();
		String mystrdate = myFormat.format(calendar.getTime());
		return Timestamp.valueOf(mystrdate);
	}

	/**
	 * yyyy-MM-dd HH:mm:ss 转换成Timestamp
	 * 
	 * @author
	 * @param timeString
	 * @return
	 */
	public static Timestamp getTime(String timeString) {
		return Timestamp.valueOf(timeString);
	}

	/**
	 * 自定义格式的字符串转换成日期
	 * 
	 * @author
	 * @param timeString
	 * @param fmt
	 * @return
	 * @throws Exception
	 */
	public static Timestamp getTime(String timeString, String fmt)
			throws Exception {
		SimpleDateFormat myFormat = new SimpleDateFormat(fmt);
		Date date = myFormat.parse(timeString);
		myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return getTime(myFormat.format(date));
	}



	/**
	 * 返回日期或者时间，如果传入的是日期，返回日期的00:00:00时间
	 * 
	 * @author
	 * @param timeString
	 * @return
	 * @throws Exception
	 */
	public static Timestamp getDateFirst(String timeString) throws Exception {
		if (timeString == null || timeString.equals("")) {
			return null;
		}
		if (timeString.length() > 10) {
			return getTime(timeString, "yyyy-MM-dd HH:mm:ss");
		} else {
			return getTime(timeString, "yyyy-MM-dd");
		}
	}

	/**
	 * 返回日期或者时间，如果传入的是日期，返回日期的23:59:59时间
	 * 
	 * @author
	 * @param timeString
	 * @return
	 * @throws Exception
	 */
	public static Timestamp getDateLast(String timeString) throws Exception {
		if (timeString == null || timeString.equals("")) {
			return null;
		}
		if (timeString.length() > 10) {
			return getTime(timeString, "yyyy-MM-dd HH:mm:ss");
		} else {
			return getTime(timeString + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
		}
	}

	/**
	 * 获取本周 周一时间，返回 格式yyyy-MM-dd 00:00:00
	 * 
	 * @author
	 * @return
	 */
	public static Timestamp getMonday() {
		Calendar calendar = Calendar.getInstance();
		int dayofweek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		if (dayofweek == 0)
		{dayofweek = 7;}
		calendar.add(Calendar.DATE, -dayofweek + 1);

		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		String mystrdate = myFormat.format(calendar.getTime());
		return Timestamp.valueOf(mystrdate);
	}

	/**
	 * 获取本周 周日 时间，返回格式yyyy-MM-dd 23:59:59
	 * 
	 * @author
	 * @return
	 */
	public static Timestamp getSunday() {
		Calendar calendar = Calendar.getInstance();
		int dayofweek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		if (dayofweek == 0)
		{dayofweek = 7;}
		calendar.add(Calendar.DATE, -dayofweek + 7);

		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
		String mystrdate = myFormat.format(calendar.getTime());
		return Timestamp.valueOf(mystrdate);
	}

	/**
	 * 增加天数
	 * 
	 * @author
	 * @param time
	 * @param day
	 * @return
	 */
	public static Timestamp addDay(Timestamp time, Integer day) {
		Timestamp time2 = new Timestamp(time.getTime() + day * 1000L * 60 * 60
				* 24);
		return time2;
	}

	/**
	 * 比较2个日期格式的字符串
	 * 
	 * @author
	 * @param str1
	 *            格式：yyyyMMdd
	 * @param str2
	 *            格式：yyyyMMdd
	 * @return
	 */
	public static Integer compareDate(String str1, String str2)
			throws Exception {

		return Integer.parseInt(str1) - Integer.parseInt(str2);

	}

	/**
	 * 间隔天数(2个时间的相差天数)
	 * 
	 * @author
	 * @param time1
	 * @param time2
	 * @return
	 */
	public static Integer getDayBetween(Timestamp time1, Timestamp time2) {
		Long dayTime = (time1.getTime() - time2.getTime())
				/ (1000 * 60 * 60 * 24);
		return dayTime.intValue();
	}

	
	/**
	 * 间隔天数
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static Integer getDayBetween(Date startDate, Date endDate) {
		Calendar start = Calendar.getInstance();
		start.setTime(startDate);
		start.set(Calendar.HOUR_OF_DAY, 0);
		start.set(Calendar.MINUTE, 0);
		start.set(Calendar.SECOND, 0);
		start.set(Calendar.MILLISECOND, 0);
		Calendar end = Calendar.getInstance();
		end.setTime(endDate);
		end.set(Calendar.HOUR_OF_DAY, 0);
		end.set(Calendar.MINUTE, 0);
		end.set(Calendar.SECOND, 0);
		end.set(Calendar.MILLISECOND, 0);

		long n = end.getTimeInMillis() - start.getTimeInMillis();
		return (int) (n / (60 * 60 * 24 * 1000L));
	}
	
	
	/**
	 * 间隔月
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static Integer getMonthBetween(Date startDate, Date endDate) {
		if (startDate == null || endDate == null || !startDate.before(endDate)) {
			return null;
		}
		Calendar start = Calendar.getInstance();
		start.setTime(startDate);
		Calendar end = Calendar.getInstance();
		end.setTime(endDate);
		int year1 = start.get(Calendar.YEAR);
		int year2 = end.get(Calendar.YEAR);
		int month1 = start.get(Calendar.MONTH);
		int month2 = end.get(Calendar.MONTH);
		int n = (year2 - year1) * 12;
		n = n + month2 - month1;
		return n;
	}

	/**
	 * 间隔月，多一天就多算一个月
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static Integer getMonthBetweenWithDay(Date startDate, Date endDate) {
		if (startDate == null || endDate == null || !startDate.before(endDate)) {
			return null;
		}
		Calendar start = Calendar.getInstance();
		start.setTime(startDate);
		Calendar end = Calendar.getInstance();
		end.setTime(endDate);
		int year1 = start.get(Calendar.YEAR);
		int year2 = end.get(Calendar.YEAR);
		int month1 = start.get(Calendar.MONTH);
		int month2 = end.get(Calendar.MONTH);
		int n = (year2 - year1) * 12;
		n = n + month2 - month1;
		int day1 = start.get(Calendar.DAY_OF_MONTH);
		int day2 = end.get(Calendar.DAY_OF_MONTH);
		if (day1 <= day2) {
			n++;
		}
		return n;
	}
	
	/**
	 * 两个日期相减 格式 yyyyMMdd
	 * 
	 * @param oldDate
	 * @param newDate
	 * @return 相差的天数
	 */
	public static Long getSubDate(String oldDate, String newDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Date d1 = null;
		Date d2 = null;
		try {
			d1 = sdf.parse(oldDate);
			d2 = sdf.parse(newDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}

		// System.out.println((d1.getTime() - d2.getTime()) / (3600L*1000*24));
		return (d1.getTime() - d2.getTime()) / (3600L * 1000 * 24);
	}

	/**
	 * 获取系统当前时间（分）
	 * 
	 * @author
	 * @return
	 */
	public static String getMinute() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMddHHmm");
		return myFormat.format(new Date());
	}

	/**
	 * 转换成时间 字符串格式必须为 yyyy-MM-dd HH:mm:ss 或 yyyy-MM-dd
	 * 
	 * @author
	 * @return
	 * @throws ParseException
	 */
	public static Date parseToDate(String val)  {
		Date date = null;
		if (val != null && val.trim().length() != 0
				&& !val.trim().toLowerCase().equals("null")) {
			val = val.trim();
			if (val.length() > 10) {
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				try {
					date = sdf.parse(val);
				} catch (ParseException e) {
					throw new RuntimeException(e);
				}
			}
			if (val.length() <= 10) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					date = sdf.parse(val);
				} catch (ParseException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return date;
	}

	/**
	 * 获取上月的第一天yyyy-MM-dd 00:00:00和最后一天yyyy-MM-dd 23:59:59
	 * 
	 * @author
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static Map<String, String> getPreMonth() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Calendar cal = Calendar.getInstance();
		GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());

		calendar.add(Calendar.MONTH, -1);
		Date theDate = calendar.getTime();
		gcLast.setTime(theDate);
		gcLast.set(Calendar.DAY_OF_MONTH, 1);
		String day_first_prevM = df.format(gcLast.getTime());
		StringBuffer str = new StringBuffer().append(day_first_prevM).append(
				" 00:00:00");
		day_first_prevM = str.toString(); // 上月第一天

		calendar.add(cal.MONTH, 1);
		calendar.set(cal.DATE, 1);
		calendar.add(cal.DATE, -1);
		String day_end_prevM = df.format(calendar.getTime());
		StringBuffer endStr = new StringBuffer().append(day_end_prevM).append(
				" 23:59:59");
		day_end_prevM = endStr.toString(); // 上月最后一天

		Map<String, String> map = new HashMap<String, String>();
		map.put("prevMonthFD", day_first_prevM);
		map.put("prevMonthPD", day_end_prevM);
		return map;
	}

	/**
	 * 获取上周 周一时间，返回 格式yyyy-MM-dd 00:00:00
	 * 
	 * @author
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static Timestamp getPreMonday() {
		Calendar calendar = Calendar.getInstance();
		int dayofweek = calendar.get(Calendar.DAY_OF_WEEK);
		System.out.println(dayofweek);
		if (dayofweek == 1) {
			calendar.add(calendar.WEEK_OF_MONTH, -1);
		}

		calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		calendar.add(calendar.WEEK_OF_MONTH, -1);

		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		String mystrdate = myFormat.format(calendar.getTime());
		return Timestamp.valueOf(mystrdate);
	}

	/**
	 * 获取上周 周日时间，返回 格式yyyy-MM-dd 23:59:59
	 * 
	 * @author
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static Timestamp getPreSunday() {
		Calendar calendar = Calendar.getInstance();
		int dayofweek = calendar.get(Calendar.DAY_OF_WEEK);
		if (dayofweek != 1) {
			calendar.add(calendar.WEEK_OF_MONTH, +1);
		}

		calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		calendar.add(calendar.WEEK_OF_MONTH, -1);

		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
		String mystrdate = myFormat.format(calendar.getTime());
		return Timestamp.valueOf(mystrdate);
	}

	public static String getDateyyyyMMddHHmmssSSS() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		Calendar calendar = Calendar.getInstance();
		return myFormat.format(calendar.getTime());
	}

	public static String getDateyyyyMMddHHmmss() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		Calendar calendar = Calendar.getInstance();
		return myFormat.format(calendar.getTime());
	}

	

	public static String getDateyyyyMMdd() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMdd");
		Calendar calendar = Calendar.getInstance();
		return myFormat.format(calendar.getTime());
	}
	public static String getDateyyyyMMdds() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		return myFormat.format(calendar.getTime());
	}
	public static String getDateMMdd() {
		SimpleDateFormat myFormat = new SimpleDateFormat("MMdd");
		Calendar calendar = Calendar.getInstance();
		return myFormat.format(calendar.getTime());
	}
	public static String getDateHHmmss() {
		SimpleDateFormat myFormat = new SimpleDateFormat("HHmmss");
		Calendar calendar = Calendar.getInstance();
		return myFormat.format(calendar.getTime());
	}
	
	/**
	 * 获取当前月份，格式yyyyMM
	 * 
	 * @return
	 */
	public static String getMonth() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMM");
		return myFormat.format(getDate());
	}
	public static String getYear() {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy");
		return myFormat.format(getDate());
	}
	/**
	 * 周一 是1 周天是7
	 * 
	 * @return
	 */
	public static int getDayOfWeek() {

		// Calendar c = Calendar.getInstance();
		// c.setTime(new Date(System.currentTimeMillis()));
		// int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

		int dayOfWeek = DateTime.now().dayOfWeek().get();

		return dayOfWeek;
	}

	/**
	 * 周一 是1 周天是7
	 * 
	 * @return
	 */
	public static int getDayOfWeek(int n) {

		// Calendar c = Calendar.getInstance();
		// c.setTime(new Date(System.currentTimeMillis()));
		// int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

		int dayOfWeek = DateTime.now().minusDays(n).dayOfWeek().get();

		return dayOfWeek;
	}
	
	/**
	 * 获取当前天 yyyyMMdd格式
	 * @return currDay  
	 */
	public static String getCurrDay() {
		String currDay = getDateyyyyMMdd();
		return currDay;
	}

	public static String getPrevDay() {

		String minusDay = null;
		try {
			minusDay = new DateTime(
					new SimpleDateFormat("yyyyMMdd").parse(getDateyyyyMMdd()))
					.minusDays(1).toString("yyyyMMdd");
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}

		return minusDay;
	}


	public static String getAfterDay() {

		String plusDay = null;
		try {
			plusDay = new DateTime(
					new SimpleDateFormat("yyyyMMdd").parse(getDateyyyyMMdd()))
					.plusDays(1).toString("yyyyMMdd");
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		return plusDay;
	}

	/**
	 * 某天的前那天日期
	 * 
	 * @param yyyyMMdd
	 * @param n
	 * @return
	 */
	public static String getPrevDay(String yyyyMMdd, Integer n) {

		String minusDay = null;
		try {
			minusDay = new DateTime(
					new SimpleDateFormat("yyyyMMdd").parse(yyyyMMdd))
					.minusDays(n).toString("yyyyMMdd");
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		return minusDay;
	}

	

	/**
	 * 某天的后n天日期
	 * @param yyyyMMdd
	 * @param n
	 * @return
	 */
	public static String getAfterDay(String yyyyMMdd, Integer n) {

		String plusDay = null;
		try {
			plusDay = new DateTime(
					new SimpleDateFormat("yyyyMMdd").parse(yyyyMMdd)).plusDays(
					n).toString("yyyyMMdd");
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		return plusDay;
	}

	
	
	
	/**
	 * 比较时间
	 * @param arg1
	 * @param arg2
	 * @return
	 */
	public static boolean compareTime(Date arg1, Date arg2) {

		long data1 = arg1.getTime();

		long data2 = arg2.getTime();

		return data1 > data2 ? true : false;

	}
	
	/**
	 * 时间累加
	 * 
	 * @param date 当前日期 格式必须为 yyyyMMddHHmmss
	 * 
	 * @param second 累加的时间 单位是秒
	 * 
	 * @return 日期
	 * 
	 * @throws ParseException 
	 */
	public static String dateAddSecond(String yyyyMMddHHmmss, Long second){

		try {
			return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date((new SimpleDateFormat("yyyyMMddHHmmss").parse(yyyyMMddHHmmss).getTime() + second * 1000)));
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

//	/**
//	 * 时间相减
//	 * 
//	 * @param date 当前日期 格式必须为 yyyyMMdd
//	 * 
//	 * @param day 累加的时间 单位是天
//	 * 
//	 * @return 日期
//	 * 
//	 * @throws ParseException 
//	 */
//	public static String dateSub(String yyyyMMdd, int day) {
//		
//		try {
//			return new SimpleDateFormat("yyyyMMdd").format(new Date((new SimpleDateFormat("yyyyMMdd").parse(yyyyMMdd).getTime() - Long.valueOf(day) * 24 * 60 * 60 * 1000)));
//		} catch (ParseException e) {
//			e.printStackTrace();
//			throw new RuntimeException(e);
//		}
//		
//	}
//	
//	/**
//	 * 时间相加
//	 * 
//	 * @param date 当前日期 格式必须为 yyyyMMdd
//	 * 
//	 * @param day 累加的时间 单位是天
//	 * 
//	 * @return 日期
//	 * 
//	 * @throws ParseException 
//	 */
//	public static String dateAdd(String yyyyMMdd, int day) {
//		
//		try {
//			return new SimpleDateFormat("yyyyMMdd").format(new Date((new SimpleDateFormat("yyyyMMdd").parse(yyyyMMdd).getTime() + Long.valueOf(day) * 24 * 60 * 60 * 1000)));
//		} catch (ParseException e) {
//			e.printStackTrace();
//			throw new RuntimeException(e);
//		}
//		
//	}
	
	
	/**
	 * 字符串转换为日期:不支持yyM[M]d[d]格式
	 * 
	 * @param date
	 * @return
	 */
	public static Date string2Date(String date) {
		if (date == null) {
			return null;
		}
		String separator = String.valueOf(date.charAt(4));
		String pattern = "yyyyMMdd";
		if (!separator.matches("\\d*")) {
			pattern = "yyyy" + separator + "MM" + separator + "dd";
			if (date.length() < 10) {
				pattern = "yyyy" + separator + "M" + separator + "d";
			}
		} else if (date.length() < 8) {
			pattern = "yyyyMd";
		}
		pattern += " HH:mm:ss.SSS";
		pattern = pattern.substring(0, Math.min(pattern.length(), date.length()));
		try {
			return new SimpleDateFormat(pattern).parse(date);
		} catch (ParseException e) {
			return null;
		}
	}
	
	/**
	 * String时间转换为Date
	 * 
	 * @param value  日期参数
	 * 
	 * @param formate 日期格式
	 * @throws ParseException 
	 */
	public static Date formateString2Date(String value, String formate)  {
		
		if (value == null){
			return null;
		}
		
		DateFormat format = new SimpleDateFormat(formate);
		
		try {
			return format.parse(value);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		
	}
	
	private static final ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>();
	private static final Object object = new Object();
	/**
     * 获取SimpleDateFormat
     * @param pattern 日期格式
     * @return SimpleDateFormat对象
     * @throws RuntimeException 异常：非法日期格式
     */
    private static SimpleDateFormat getDateFormat(String pattern)  {
        SimpleDateFormat dateFormat = threadLocal.get();
        if (dateFormat == null) {
            synchronized (object) {
                if (dateFormat == null) {
                    dateFormat = new SimpleDateFormat(pattern);
                    dateFormat.setLenient(false);
                    threadLocal.set(dateFormat);
                }
            }
        }
        dateFormat.applyPattern(pattern);
        return dateFormat;
    }
	  /**
     * 将日期转化为日期字符串。失败返回null。
     * @param date 日期
     * @param pattern 日期格式
     * @return 日期字符串
     */
    public static String DateToString(Date date, String pattern) {
        String dateString = null;
        if (date != null) {
            try {
                dateString = getDateFormat(pattern).format(date);
            } catch (Exception e) {
            }
        }
        return dateString;
    }
	
	

	public static void main(String[] agrs) {
		//System.out.println(getPrevDay());
		System.out.println(getDayOfWeek(2));
		try {
			System.out.println(getDateMMdd());;
			System.out.println(getDateHHmmss());
			System.out.println(dateAddSecond("20141108235945", 60L));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
